package org.smart4j.chapter2.helper;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.chapter2.util.PropsUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by 16060457 on 2017/10/16.
 */
public class DatabaseHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);
    private static final QueryRunner QUERY_RUNNER = new QueryRunner();
    private static final ThreadLocal<Connection> CONNECTION_HOLDER = new ThreadLocal<Connection>();
    private static final BasicDataSource DATA_SOURCE = new BasicDataSource();

    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    static {
        Properties conf = PropsUtil.loadProps("config.properties");
        DRIVER = conf.getProperty("jdbc.driver");
        URL = conf.getProperty("jdbc.url");
        USERNAME = conf.getProperty("jdbc.username");
        PASSWORD = conf.getProperty("jdbc.password");

        DATA_SOURCE.setDriverClassName(DRIVER);
        DATA_SOURCE.setUrl(URL);
        DATA_SOURCE.setUsername(USERNAME);
        DATA_SOURCE.setPassword(PASSWORD);

        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() {
        Connection conn = CONNECTION_HOLDER.get();
        if (conn == null) {
            try {
                // 从数据库连接池获取连接
                conn = DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                LOGGER.error("get connection failure", e);
                throw new RuntimeException(e);
            } finally {
                CONNECTION_HOLDER.set(conn);
            }
        }
        return conn;
    }

    /**
     * 查询实体列表
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
        List<T> entityList;
        try {
            Connection conn = getConnection();
            entityList = QUERY_RUNNER.query(conn, sql, new BeanListHandler<T>(entityClass), params);
        } catch (SQLException e) {
            LOGGER.error("query entity list failure.", e);
            throw new RuntimeException(e);
        }
        return entityList;
    }

    /**
     * 查询实体
     */
    public static <T> T queryEntity(Class<T> entityTClass, String sql, Object... params) {
        T entity = null;
        try {
            Connection conn = getConnection();
            entity = QUERY_RUNNER.query(conn, sql, new BeanHandler<T>(entityTClass), params);
        } catch (SQLException e) {
            LOGGER.error("query entity failure", e);
            throw new RuntimeException(e);
        }
        return entity;
    }

    /**
     * 执行查询语句
     */
    public static List<Map<String, Object>> executeQuery(String sql, Object...
            params) {
        List<Map<String, Object>> result = null;
        try {
            Connection conn = getConnection();
            result = QUERY_RUNNER.query(conn, sql, new MapListHandler(), params);
        } catch (Exception e) {
            LOGGER.error("execute query failure", e);
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 执行更新语句（包括 update、insert、delete）
     */
    public static int executeUpdate(String sql, Object... params) {
        int rows = 0;
        try {
            Connection conn = getConnection();
            rows = QUERY_RUNNER.update(conn, sql, params);
        } catch (SQLException e) {
            LOGGER.error("execute update failure", e);
            throw new RuntimeException(e);
        }
        return rows;
    }

    /**
     * 删除实体
     */
    public static <T> boolean deleteEntity(Class<T> entityTClass, long id) {
        String sql = "DELETE FROM " + getTableName(entityTClass) + " WHERE id = ?";
        return executeUpdate(sql, id) == 1;
    }

    /**
     * 更新实体
     */
    public static <T> boolean updateEntity(Class<T> entityTClass, long id, Map<String, Object> fieldMap) {
        String sql = "UPDATE " + getTableName(entityTClass) + " SET " + convertMapKeyToSqlParams(fieldMap)+ "WHERE id = ?";
        Iterator<Map.Entry<String, Object>> iterator = fieldMap.entrySet().iterator();
        List<Object> list = new ArrayList<Object>();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            list.add(entry.getValue());
        }
        list.add(id);
        return executeUpdate(sql, list.toArray()) == 1;
    }

    /**
     * 插入实体
     */
    public static <T> boolean insertEntity(Class<T> entityTClass, Map<String, Object> fieldMap) {
        String sql = "INSERT INTO " + getTableName(entityTClass) + convertMapToSqlParams(fieldMap);
        System.out.println(sql);
        Iterator<Map.Entry<String, Object>> iterator = fieldMap.entrySet().iterator();
        List<Object> list = new ArrayList<Object>();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            list.add(entry.getValue());
        }
        return executeUpdate(sql, list.toArray()) == 1;
    }


    /**
     * 获取表名
     */
    private static <T> String getTableName(Class<T> entityTClass) {
        return entityTClass.getSimpleName();
    }

    /**
     * 把map入参转为update语句参数
     */
    private static String convertMapKeyToSqlParams(Map<String, Object> fieldMap) {
        StringBuilder params = new StringBuilder();
        Set<String> keySet = fieldMap.keySet();
        for (String key : keySet) {
            params.append(key).append(" = ?, ");
        }
        params.deleteCharAt(params.lastIndexOf(","));
        return params.toString();
    }

    /**
     * 把map入参转为insert语句参数
     */
    private static String convertMapToSqlParams(Map<String, Object> fieldMap) {
        StringBuilder keys = new StringBuilder("(");
        StringBuilder params = new StringBuilder("(");
        Iterator<Map.Entry<String, Object>> iterator = fieldMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            keys.append(entry.getKey()).append(",");
            params.append("?, ");
        }
        keys.deleteCharAt(keys.lastIndexOf(","));
        params.deleteCharAt(params.lastIndexOf(","));
        keys.append(") VALUES ");
        params.append(");");
        return keys.toString() + params.toString();
    }

    /**
     * 执行SQL文件中的语句
     * @param filePath
     */
    public static void executeSqlFile(String filePath) {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String sql;
        try {
            while((sql = reader.readLine()) != null) {
                DatabaseHelper.executeUpdate(sql);
            }
        } catch (IOException e) {
            LOGGER.error("execute sql file failure", e);
            throw new RuntimeException(e);
        }
    }
}

